var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) !== "micromessenger") {
  document.body.innerHTML = navigator.userAgent;
} else {
  var userInputDOM = document.getElementsByClassName("input")[0];
  var userSubmit = document.getElementsByClassName("choose_avatar")[0];
  var loadDOM=document.getElementsByClassName("loading")[0];
  userInputDOM.oninput = function () {
    userInputDOM.value = userInputDOM.value.replace(/[^\d]/g, '')
  }
  userSubmit.onclick = function (e) {
    var i=e.target.getAttribute("i");
    if(i){
      loadDOM.innerHTML="加载中...";
      draw(userInputDOM.value,i);
    }
  }
}
function draw(qq, file) {
  var draw = document.getElementsByClassName("draw")[0];
  var download=document.getElementsByClassName("download")[0];
  var ctx = draw.getContext("2d");
  var userAvatar = new Image(175, 175);
  var userChoose = new Image(175, 175);
  userAvatar.src = "http://47.108.165.1:8889/headphoto/" + qq ;
  userChoose.crossOrigin="";
  userAvatar.crossOrigin="";
  var xhr = new XMLHttpRequest();
  var isDraw = false;
  var loadFinish = false;
  xhr.open("GET", "./" + file + ".txt");
  var Header = "";
  xhr.onload = function () {
    Header = window.atob(xhr.response.replace(/-/g, "a"));
    userChoose.src = Header;
    userChoose.onload = function () {
      if (loadFinish) {
        isDraw = true;
        draw.classList.add("show");
        loadDOM.innerHTML="";
        ctx.drawImage(userAvatar, 0, 0, 250, 250);
        ctx.drawImage(userChoose, 0, 0,250,250);
        var imgData =draw.toDataURL({format: 'png', quality:1, width:250, height:250});
        var blob = dataURLtoBlob(imgData);
        var objurl = URL.createObjectURL(blob);
              download.href=objurl;
              console.log(objurl);
              download.download="avatar.png";
      }
    }
  }
  userAvatar.onload = function () {
    loadFinish = true;
    if (!isDraw) {
      draw.classList.add("show");
      loadDOM.innerHTML="";
      ctx.drawImage(userAvatar, 0, 0, 250, 250);
      ctx.drawImage(userChoose, 0, 0,250,250);
      var imgData =draw.toDataURL({format: 'png', quality:1, width:250, height:250});
var blob = dataURLtoBlob(imgData);
var objurl = URL.createObjectURL(blob);
      download.href=objurl;
      console.log(objurl);
      download.download="avatar.png";
    }
  }
  xhr.send();
}

function  dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type:mime});
}